package com.example.applicationnews;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import com.example.applicationnews.ui.main.SectionsPagerAdapter;
import com.google.android.material.tabs.TabLayout;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = MainActivity.this;
        // 初始化新闻列表，从网络下载并写入到文件中
        initialNewsList();

        SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
        ViewPager viewPager = findViewById(R.id.view_pager);
        viewPager.setAdapter(sectionsPagerAdapter);
        TabLayout tabs = findViewById(R.id.news_tabs);
        tabs.setupWithViewPager(viewPager);
    }

    void initialNewsList() {
        String[] typeList = {"shehui", "guonei", "guoji", "xiaohua", "yule"};
        for (String type: typeList) {
            // 子线程下载接口数据
            newsCache(type);
            Log.d(TAG, "onCreate: foreach: " + type);
        }
    }

    void newsCache(String type) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL("http://newswifiapi.dftoutiao.com/newspool/topnews?type=" + type);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    InputStream is = connection.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
                    StringBuilder result = new StringBuilder();
                    String line = "";
                    while ((line = bufferedReader.readLine())!=null){
                        result.append(line).append("\n");
                    }

                    String finalResult = result.toString();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.d(TAG, "run: download data" + finalResult);
                            try {
                                // 保存数据到本地
                                saveNews(type, finalResult);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    void saveNews(String type, String result) throws IOException {
        FileHelper fHelper = new FileHelper(mContext);
        String fileName = type + ".json";
        try {
            fHelper.save(fileName, result);
            Log.d(TAG, "saveNews: 数据写入成功");
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG, "saveNews: 数据写入失败");
        }
    }
}